import 'package:distribution_mall_flutter/constant/status_constant.dart';
import 'package:distribution_mall_flutter/entity/address/address_entity.dart';
import 'package:distribution_mall_flutter/entity/order/list/order_list_entity.dart';
import 'package:distribution_mall_flutter/entity/order/order.dart';
import 'package:distribution_mall_flutter/generated/l10n.dart';
import 'package:distribution_mall_flutter/http/modules/order.dart';
import 'package:distribution_mall_flutter/utils/common_third.dart';
import 'package:distribution_mall_flutter/utils/log.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:permission_handler/permission_handler.dart';

List<Map<String, String>> tabMap = [
  {'label': S.current.all, 'value': ''},
  {
    'label': S.current.order_status_to_pay,
    'value': OrderStatusEnum.toPay.status
  },
  {
    'label': S.current.order_status_to_confirmed,
    'value': OrderStatusEnum.waitConfirm.status
  },
  {
    'label': S.current.order_status_preparing,
    'value': OrderStatusEnum.preparing.status
  },
  {
    'label': S.current.order_status_shipped,
    'value': OrderStatusEnum.shipped.status
  },
  {
    'label': S.current.order_status_completed,
    'value': OrderStatusEnum.completed.status
  },
  {
    'label': S.current.order_status_closed,
    'value': OrderStatusEnum.closed.status
  },
];

Item _item = const Item();
List<Item> _list = [_item, _item, _item, _item];

class OrderListState {
  List<Item> list;
  int page;
  int size;
  LoadStatus load;
  bool firstLoading;
  bool loading;
  List<OrderTransportEntity> transportList;
  Map<String, dynamic> params;

  OrderListState(
      {this.list = const [],
      this.page = 1,
      this.size = 20,
      this.load = LoadStatus.allow, // 0都可  1刷新  2加载中 3 空了
      this.firstLoading = false,
      this.loading = false,
      this.transportList = const [],
      this.params = const {}});

  OrderListState.initial()
      : list = _list,
        page = 1,
        size = 20,
        load = LoadStatus.allow,
        firstLoading = false,
        loading = false,
        transportList = const [],
        params = const {};

  OrderListState copyWith(
          {List<Item>? list,
          int? page,
          int? size,
          LoadStatus? load,
          bool? loading,
          bool? upOrAddLoading,
          bool? firstLoading,
          List<AddressDeliveryTimeEntity>? addrDeTime,
          Future<dynamic> Function(Map<String, dynamic> arg)? onRefresh,
          ScrollController? scrollController,
          String? regionStr,
          List<OrderTransportEntity>? transportList,
          Map<String, dynamic>? params}) =>
      OrderListState(
        list: list ?? this.list,
        page: page ?? this.page,
        size: size ?? this.size,
        load: load ?? this.load,
        firstLoading: firstLoading ?? this.firstLoading,
        loading: loading ?? this.loading,
        transportList: transportList ?? this.transportList,
        params: params ?? this.params,
      );
}

final orderListProvider =
    StateNotifierProvider.autoDispose<OrderListViewModel, OrderListState>(
        (ref) {
  return OrderListViewModel();
});

class OrderListViewModel extends StateNotifier<OrderListState> {
  OrderListViewModel() : super(OrderListState.initial());

  Future onLoadMore() async {
    if (state.load == LoadStatus.empty) return LoadStatus.empty;
    state = state.copyWith(load: LoadStatus.loading);
    return await initData();
  }

  Future<LoadStatus> initData(
      [Map<String, dynamic> map = const {}, showLoading = false]) async {
    // if (state.loading == true) return LoadStatus.loading;

    state = state.copyWith(
        loading: true, page: state.load == LoadStatus.refresh ? 1 : state.page);
    try {
      OrderListEntity apiData = await OrderApi.orderQuery({
        ...state.params,
        ...map,
        'pageCondition': {
          'pageNum': state.page,
          'pageSize': state.size,
        }
      }, false);
      Future.delayed(const Duration(milliseconds: 500), () {
        state = state.copyWith(firstLoading: false);
      });

      List<Item> data = apiData.items ?? [];

      if (state.page == 1 || state.load == LoadStatus.refresh) {
        state = state.copyWith(list: data);
      } else {
        state = state.copyWith(list: [...(state.list), ...data]);
      }
      state = state.copyWith(
          load: data.isEmpty ? LoadStatus.empty : LoadStatus.allow,
          page: ++state.page);
    } catch (e) {
      LogUtil.d(e);
      if (state.firstLoading) {
        state = state.copyWith(list: []);
      }
    } finally {
      EPLoading.dis();
      Future.delayed(const Duration(milliseconds: 500), () {
        state = state.copyWith(
            loading: false,
            firstLoading: false,
            load: state.load == LoadStatus.refresh
                ? LoadStatus.allow
                : state.load);
      });
    }

    return state.load;
  }

  Future refresh(
      [Map<String, dynamic> map = const {}, bool showLoading = false]) async {
    if (state.load == LoadStatus.refresh) {
      EPLoading.dis();
      return LoadStatus.operationing;
    }
    state = state.copyWith(load: LoadStatus.refresh);
    return await initData(map, showLoading);
  }

  Future<bool> deleteOrder(Map<String, dynamic> params) async {
    bool bol = false;
    EPLoading.showLoadig();
    try {
      bol = await OrderApi.orderDelete(params);
      if (!bol) return false;
      refresh();
      return true;
    } catch (e) {
      return false;
    } finally {
      EPLoading.dis();
    }
  }

  getTransportType() async {
    List<OrderTransportEntity>? data = (await OrderApi.orderTransport({})).data;
    if (data == null) return;
    state = state.copyWith(transportList: data);
  }

  String getTransportName(String? type) {
    if (type == null || type.isEmpty) return '';
    for (OrderTransportEntity item in state.transportList) {
      if (item.code == type) return item.name ?? '';
    }
    return '';
  }

  setParams(Map<String, dynamic>? map) {
    state =
        state.copyWith(params: map == null ? {} : {...state.params, ...map});
  }

  setParamsAndRefresh(Map<String, dynamic>? map) {
    setParams(map);
    refresh();
  }

  setFirstLoading() {
    state = state.copyWith(firstLoading: true);
  }
}
